package com.vtron.web.api.advice;

import com.alibaba.fastjson.JSON;
import com.vtron.core.HttpCode;
import com.vtron.core.HttpResult;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 统一返回数据结果
 * @date : 2021/12/30 10:34
 * @author: 忻龙彪
 */

@RestControllerAdvice
public class RestApiDataAdvice implements ResponseBodyAdvice {
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        HttpResult result = new HttpResult();
        //获取返回值类型
        String returnClassType = returnType.getParameterType().getSimpleName();
        if ("String".equals(returnClassType)) {
            result = new HttpResult(body);
            return JSON.toJSONString(result);
        }
        if ("HttpResult".equals(returnClassType)) {
            return (HttpResult) body;
        }
        if ("void".equals(returnClassType)) {
            result = new HttpResult();
        } else {
            result = new HttpResult(body);
        }
        return result;
    }

    @ExceptionHandler(Exception.class)
    public HttpResult parseRuntimeException(Exception ex) {
        ex.printStackTrace();
        HttpResult result = new HttpResult();
        result.message=ex.getMessage();
        result.status= HttpCode.FAIL.getValue();
        return result;
    }
}
